package com.gmrz.uaf.protocol.v1.processor;

import com.gmrz.uaf.db.DAOException;
import com.gmrz.uaf.db.UAFDAOFactory;
import com.gmrz.uaf.db.UAFDBConnectionMgr;
import com.gmrz.uaf.db.dao.AuthenticatorDAO;
import com.gmrz.uaf.protocol.v1.json.UAFSchemaBuilder;
import com.gmrz.uaf.protocol.v1.processor.exception.AdditionUviException;
import com.gmrz.uaf.protocol.v1.processor.exception.UAFErrorCode;
import com.gmrz.uaf.protocol.v1.schema.*;
import com.gmrz.util.db.DBUtil;
import com.google.common.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chentaikun on 16/12/19.
 */
public class UAFAddUviProcessor extends UAFBaseProcessor {

    private static final Logger LOG = LogManager.getLogger(UAFAddUviProcessor.class);

    /**
     * 增加指纹
     * @param additionUvi
     * @throws AdditionUviException
     * @throws SQLException
     * @throws DAOException
     */
    public void addUvi(AdditionUvi additionUvi) throws AdditionUviException, SQLException, DAOException {
        long addUviTime = additionUvi.getTime();
        if((System.currentTimeMillis() - addUviTime) > serverConfig.getAddUviTimeOut()){
            throw new AdditionUviException(UAFErrorCode.PROTOCOL_ADD_UVI_TIME_OUT);
        }
        Connection conn = UAFDBConnectionMgr.getConnection();
//        AuthenticatorDAO adao = GuiceUtil.getProcessorInjector().getInstance(DAOFactory.class)
//                .createAuthenticatorDAO(conn);
        try {
            AuthenticatorDAO adao = UAFDAOFactory.createAuthenticatorDAO(conn);
            String appID = additionUvi.getAppID();
            String userName = additionUvi.getUserName();
            String aaid = additionUvi.getAaid();
            String keyID = additionUvi.getKeyID();
            String uvi = additionUvi.getUvi();
            Authenticator authenticator = adao.findUser(appID, userName, aaid, keyID);
            if (null != authenticator) {
                List<String> uvs = authenticator.getUvs();
                if (null != uvs) {
                    if(uvs.size() >= 5){
                        LOG.info("Addition uvi :" + uvi + ",user :" + authenticator.getUserName() + ", exceed max num");
                        throw new AdditionUviException(UAFErrorCode.PROTOCOL_ADD_UVI_MAX_LENGTH);
                    }
                    uvs.add(uvi);
                } else {
                    uvs = new ArrayList<String>();
                    uvs.add(uvi);
                }
                String uvsJson = UAFSchemaBuilder.getGson().toJson(uvs, new TypeToken<List<String>>() {
                }.getType());
                adao.addUvi(appID, userName, aaid, keyID, uvsJson, uvi);
            }
        }catch (DAOException e1){
            LOG.error("addUvi error",e1);
        }finally {
            DBUtil.close(conn);
        }


    }
}
